import router from "@/router/index";
import store from "@/store";

//路由守卫
router.beforeEach((to,from,next)=>{
    const whiteList=['/login'] //白名单
    let token=store.getters.GET_TOKEN;
    //是否已经动态绑定了路由的标识
    let hasRoutes = store.state.hasRoutes;
    let menuList = store.getters.GET_MENULIST;

    if(token){
        if(!hasRoutes){
            //动态添加路由
            bindRoute(menuList);
            store.commit("SET_ROUTES_STATE",true);
        }
        next();
    }else {
        if(whiteList.includes(to.path)){
            next()
        }else{
            next("/login")
        }
    }
})

//动态绑定路由方法
const bindRoute=(menuList)=>{
    let newRoutes = router.options.routes;
    //遍历菜单列表找出子菜单
    menuList.forEach(menu=>{
        if(menu.children){
            menu.children.forEach(m=>{
                let route = menuToRoute(m,menu.name);
                if(route){
                    newRoutes[0].children.push(route);
                    // console.log("Added route:", route);
                }
            })
        }
    })
    //重新添加到路由
    newRoutes.forEach(route=>{
        router.addRoute(route)
    })
}
//动态绑定路由方法
// const bindRoute = (menuList, store) => {
//     let newRoutes = [];
//     //遍历菜单列表找出子菜单
//     menuList.forEach(menu => {
//         if (menu.children) {
//             menu.children.forEach(m => {
//                 let route = menuToRoute(m, menu.name);
//                 if (route) {
//                     newRoutes.push(route); // 将生成的路由信息存入newRoutes数组中
//                 }
//             });
//         }
//     });
//     // 将新生成的路由信息存入store.state.routes
//     store.commit('SET_ROUTES', newRoutes);
//     // 重新添加到路由
//     newRoutes.forEach(route => {
//         router.addRoute(route);
//     });
// };

//将菜单对象转成路由对象方法
const menuToRoute=(menu,parentName)=>{
    if(!menu.component){
        return null;
    }else{
        let route={
            name:menu.name,
            path:menu.path,
            meta:{
                parentName:parentName
            }
        }
        route.component=()=>import('@/views/'+menu.component+'.vue');
        return route;
    }
}